package com.ly.juc;
import	java.util.concurrent.TimeUnit;

/**
 * @Classname Lock8
 * @Description TODO
 * @Date 2020/10/4 14:29
 * @Author 冷心影翼
 */
public class Lock8 {

	public static void main(String[] args) throws InterruptedException {
//		lock1();
//		lock2();
//		lock3();
//		lock4();
//		lock5();
//		lock6();
	}

	//两个非静态sync方法，锁住的是this对象,不同对象不会被锁住
	public static void lock1() throws InterruptedException {
	    new Thread(()->new P().syncSleep()).start();
	    TimeUnit.SECONDS.sleep(1);
	    new Thread(()->new P().sync()).start();
	}

	//两个非静态sync方法，锁住的是this对象,相同对象会被锁住
	public static void lock2() throws InterruptedException {
		P p = new P();
		new Thread(()->p.syncSleep()).start();
		TimeUnit.SECONDS.sleep(1);
		new Thread(()->p.sync()).start();
	}

	//普通方法不受锁的影响
	public static void lock3() throws InterruptedException {
		P p = new P();
		new Thread(()->p.syncSleep()).start();
		TimeUnit.SECONDS.sleep(1);
		new Thread(()->p.normal()).start();
	}

	//两个静态同步方法，锁住的是class模板，相同对象,不同对象都会被锁住
	public static void lock4() throws InterruptedException {
		P p1 = new P();
		P p2 = new P();
		new Thread(()->p1.staticSyncSleep()).start();
		TimeUnit.SECONDS.sleep(1);
		new Thread(()->p2.staticSync()).start();
	}

	//一个静态同步方法，一个同步方法,一个锁住的是class模板，一个锁的是对象.
	public static void lock5() throws InterruptedException {
		P p = new P();
		new Thread(()->P.staticSyncSleep()).start();
		TimeUnit.SECONDS.sleep(1);
		new Thread(()->p.sync()).start();
	}

	//一个静态同步方法，普通方法，普通方法不受影响
	public static void lock6() throws InterruptedException {
		P p = new P();
		new Thread(()->P.staticSyncSleep()).start();
		TimeUnit.SECONDS.sleep(1);
		new Thread(()->p.normal()).start();
	}


}

class P{

	public synchronized  void syncSleep()  {
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("syncSleep");
	}

	public synchronized void sync() {
		System.out.println("sync");
	}

	public void normal() {
		System.out.println("normal");
	}
	
	public static synchronized void staticSyncSleep() {
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("staticSyncSleep");
	}
	
	public static synchronized void staticSync() {
		System.out.println("staticSync");
	}
}
